﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace _082.控制器筛选器
{
    // 请求限流器 一秒钟内只允许最多有一个来自同一个IP地址的请求
    public class RateLimitFilter : IAsyncActionFilter
    {
        private readonly IMemoryCache memCache;
        public RateLimitFilter(IMemoryCache memCache)
        {
            this.memCache = memCache;
        }
        public Task OnActionExecutionAsync(ActionExecutingContext context,
                ActionExecutionDelegate next)
        {
            string removeIP = context.HttpContext.Connection.RemoteIpAddress.ToString();
            string cacheKey = $"LastVisitTick_{removeIP}";
            long? lastTick = memCache.Get<long?>(cacheKey);
            if (lastTick == null || Environment.TickCount64 - lastTick > 1000)
            {
                memCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));
                return next();
            }
            else
            {
                ObjectResult result = new ObjectResult("访问太频繁") { StatusCode = 429 };
                context.Result = result;
                return Task.CompletedTask;
            }
        }
    }
}